package com.zuul.simple.http;

import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : kebukeyi
 * @date :  2021-05-21 11:31
 * @description :
 * 这个是网关的入口，逻辑也十分简单，分为三步
 * (1)将request,response放入threadlocal中
 * (2)执行三组过滤器
 * (3)清除threadlocal中的的环境变量
 * @question :
 * @usinglink : https://blog.csdn.net/weixin_29783407/article/details/114891114?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242
 **/
@Component
@WebServlet(name = "myZuul", urlPatterns = "/*")
public class MyZuulServlet extends HttpServlet {

    private ZuulRunner zuulRunner = new ZuulRunner();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将request和response放入上下文对象中
        zuulRunner.init(req, resp);
        try {
            //执行前置过滤
            zuulRunner.preRoute();
            //执行过滤
            zuulRunner.route();
            //执行后置过滤
            zuulRunner.postRoute();
        } catch (Throwable e) {
            RequestContext.getCurrentContext().getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } finally {
            //清除变量
            RequestContext.getCurrentContext().unset();
        }
    }
}
 
